<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>旅行社系统 - 仪表盘</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <link rel="stylesheet" href="css/main.css">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="js/api/config.js"></script>
    <script src="js/api/auth.js"></script>
</head>
<body>
    <div id="app">
        <div class="container-fluid">
            <div class="row">
                <sidebar-nav 
                    current-page="dashboard"
                    @logout="handleLogout">
                </sidebar-nav>

                <!-- 主内容区 -->
                <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                        <h1 class="h2">仪表盘</h1>
                        <div v-if="loadError" class="text-danger">
                            <i class="bi bi-exclamation-triangle"></i> 
                            数据加载失败，请稍后刷新重试
                        </div>
                    </div>

                    <!-- 统计卡片 -->
                    <div class="row">
                        <div class="col-md-4 mb-4">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">待处理订单</h5>
                                    <p class="card-text h2">{{ stats.pendingOrders || '-' }}</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 mb-4">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">本月订单</h5>
                                    <p class="card-text h2">{{ stats.monthlyOrders || '-' }}</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 mb-4">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">本月营业额</h5>
                                    <p class="card-text h2">¥{{ formatPrice(stats.monthlyRevenue || 0) }}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </main>
            </div>
        </div>
    </div>

    <div class="ai-assistant" @click="toggleChat">
        <img src="images/ai-assistant.png" alt="AI助手">
    </div>

    <div class="chat-dialog" v-if="showChat">
        <div class="chat-header">
            <h6 class="mb-0">AI助手</h6>
        </div>
        <div class="chat-messages" ref="messageContainer">
            <div v-for="(message, index) in messages" 
                 :key="index" 
                 :class="['message', message.type]">
                {{ message.content }}
            </div>
        </div>
        <div class="chat-input-container">
            <input type="text" 
                   class="chat-input" 
                   v-model="userInput" 
                   @keyup.enter="sendMessage" 
                   placeholder="输入您的问题...">
            <button class="btn btn-primary btn-sm" @click="sendMessage">
                <i class="bi bi-send"></i>
            </button>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        // 验证登录状态
        const userStr = localStorage.getItem(API_CONFIG.USER_KEY);
        console.log('Dashboard auth check:', {
            hasUserStr: !!userStr,
            userData: userStr ? JSON.parse(userStr) : null,
            localStorage: {
                keys: Object.keys(localStorage),
                length: localStorage.length
            }
        });

        if (!userStr) {
            console.error('No user data found, redirecting to login');
            window.location.href = '/login.html';
        } else {
            // 只在验证通过后加载其他脚本
            const scripts = [
                'https://cdn.jsdelivr.net/npm/vue@2.6.14',
                'js/components/Sidebar.js'
            ];
            
            function loadScript(index) {
                if (index >= scripts.length) {
                    initializeVue();
                    return;
                }
                const script = document.createElement('script');
                script.src = scripts[index];
                script.onload = () => loadScript(index + 1);
                document.body.appendChild(script);
            }
            
            loadScript(0);
        }

        function initializeVue() {
            // Vue 初始化代码
            new Vue({
                el: '#app',
                data: {
                    stats: {},
                    showChat: false,
                    userInput: '',
                    messages: [
                        {
                            type: 'assistant',
                            content: '你好！我是你的AI助手，有什么可以帮你的吗？'
                        }
                    ],
                    currentUser: null,
                    loadError: false
                },
                async created() {
                    console.log('Dashboard Vue instance created');
                    // 添加延时
                    await new Promise(resolve => setTimeout(resolve, 3000));
                    
                    try {
                        // 只打印日志，不做重定向
                        const userData = auth.getUser();
                        console.log('Dashboard loaded user data:', {
                            hasData: !!userData,
                            username: userData?.username,
                            hasToken: !!userData?.access_token
                        });
                        // 添加延时
                        await new Promise(resolve => setTimeout(resolve, 3000));
                        
                        if (userData) {
                            this.currentUser = userData;
                            await this.loadStats();
                        }
                    } catch (error) {
                        console.error('Failed to load user data:', error);
                        // 添加延时
                        await new Promise(resolve => setTimeout(resolve, 3000));
                        this.loadError = true;
                    }
                },
                methods: {
                    async loadStats() {
                        try {
                            console.log('Loading dashboard stats...');
                            const response = await window.apiClient.get('/api/stats/dashboard');
                            this.stats = response.data;
                        } catch (error) {
                            console.error('加载统计数据失败:', error);
                            // 设置默认值
                            this.stats = {
                                pendingOrders: '-',
                                monthlyOrders: '-',
                                monthlyRevenue: 0
                            };
                            this.loadError = true;
                        }
                    },
                    formatPrice(price) {
                        return price.toLocaleString('zh-CN', {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2
                        });
                    },
                    handleLogout() {
                        auth.logout();
                    },
                    toggleChat() {
                        this.showChat = !this.showChat;
                        if (this.showChat) {
                            this.$nextTick(() => {
                                this.scrollToBottom();
                            });
                        }
                    },
                    async sendMessage() {
                        if (!this.userInput.trim()) return;

                        // 添加用户消息
                        this.messages.push({
                            type: 'user',
                            content: this.userInput
                        });

                        const userQuestion = this.userInput;
                        this.userInput = '';

                        try {
                            // 调用后端API获取AI响应
                            const response = await window.apiClient.post('/api/ai/chat', {
                                message: userQuestion
                            });

                            // 添加AI响应
                            this.messages.push({
                                type: 'assistant',
                                content: response.data.reply
                            });
                        } catch (error) {
                            console.error('AI响应失败:', error);
                            this.messages.push({
                                type: 'assistant',
                                content: '抱歉，我现在无法回答您的问题。请稍后再试。'
                            });
                        }

                        this.$nextTick(() => {
                            this.scrollToBottom();
                        });
                    },
                    scrollToBottom() {
                        const container = this.$refs.messageContainer;
                        container.scrollTop = container.scrollHeight;
                    }
                }
            });
        }
    </script>
</body>
</html> 